package su.msk.jet.team01.chatik.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import su.msk.jet.team01.chatik.client.ui.UserInterface;

import java.io.IOException;

public class UIInputHandler extends Thread {

	private static Logger logger = LoggerFactory.getLogger(UIInputHandler.class);

	private ClientApplication app;
	private UserInterface ui;

	public UIInputHandler(final ClientApplication app, final UserInterface ui) {
		this.app = app;
		this.ui = ui;
	}

	private void printHelp() {
		ui.printMessage("Commands Help:\n"
				+ "/help - print this help\n"
				+ "/connect <server> <port> - connect to <server> at <port>\n"
				+ "...other commands available only in online mode...");
	}

	@Override
	public void run() {
		String userInput;
		printHelp();

		try {
			while (true) {
				userInput = ui.readMessage();
				processUserInput(userInput);
			}
		} finally {
			app.close();
		}
	}

	private void processUserInput(String userInput) {
		if(!app.connected()) {
			if (userInput.startsWith("/connect")) {
				processConnectCommand(userInput);
			} else if (userInput.startsWith("/help")) {
				printHelp();
			} else {
				ui.printMessage("You should be online to write messages");
			}
		} else {
			sendMessage(userInput);
		}
	}

	private void processConnectCommand(String userInput) {
		String host;
		String[] splited = userInput.split(" ");
		int port;
		
		try {
			host = splited[1];
			port = Integer.valueOf(splited[2]);
			app.connect(host, port);
		} catch (ArrayIndexOutOfBoundsException e) {
			ui.printMessage("Invalid syntax");
		} catch (NumberFormatException e) {
			ui.printMessage("Invalid syntax");
		}
	}

	private void sendMessage(String msg) {
		if (msg != null) {
			try {
				if (app.connected() && !msg.isEmpty()) {
					app.output().writeObject(msg);
					app.output().flush();
				}
			} catch (IOException ex) {
				logger.error("Error sending message.", ex);
			}
		}
	}

}
